package com.lazy.core.service.impl;

import com.lazy.core.entity.ActivityInfo;
import com.lazy.core.mapper.ActivityInfoMapper;
import com.lazy.core.service.ActivityInfoService;
import com.lazy.core.service.QiNiuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class ActivityInfoServiceImpl implements ActivityInfoService {

    @Value("${qiniu.file.url}")
    String qiniuFileUrl;

    @Autowired
    QiNiuService qiNiuService;
    @Autowired
    ActivityInfoMapper activityInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveOrUpdate(MultipartFile file, ActivityInfo activityInfo) {
        Integer count = 0;

        //判断文件是否为null
        if(null != file){
            byte[] uploadBytes = new byte[0];
            try {
                uploadBytes = file.getBytes();
                ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
                String fileName = file.getOriginalFilename();
                String saveFileName = qiNiuService.byteInputStreamUpload(byteInputStream,fileName);
                activityInfo.setPicture(saveFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(null == activityInfo.getId()){
            count = activityInfoMapper.insertSelective(activityInfo);
        }else{
            count = activityInfoMapper.updateByPrimaryKey(activityInfo);
        }

        return count;
    }

    @Override
    public ActivityInfo getLastActivityInfo() {
        ActivityInfo activityInfo = activityInfoMapper.getLastActivityInfo();
        if(null != activityInfo.getPicture()){
            activityInfo.setPicture(qiniuFileUrl+activityInfo.getPicture());
        }
        return activityInfo;
    }
}
